Variables are containers that you can store values in. You start by declaring a variable with the
var
keyword, followed by any name you want to call it:
var myVariable;
After declaring a variable, you can give it a value:
myVariable = 'Bob';
You can do both these operations on the same line if you wish:
var myVariable = 'Bob';
You can retrieve the value by just calling the variable by name:
myVariable;
After giving a variable a value, you can later choose to change it:
var myVariable = 'Bob'; myVariable = 'Steve';
Note that variables may hold values that have different data types:
Variable | Explanation | Example |
---|---|---|
String | A sequence of text known as a string. To signify that the value is a string, you must enclose it in quote marks. |
var myVariable = 'Bob';
|
Number | A number. Numbers don't have quotes around them. |
var myVariable = 10;
|
Boolean | A True/False value. The words
true and
false are special keywords in JS, and don't need quotes. |
var myVariable = true;
|
Array | A structure that allows you to store multiple values in one single reference. |
var myVariable = [1,'Bob','Steve',10];
Refer to each member of the array like this: myVariable[0] ,
myVariable[1] , etc. |
Object | Basically, anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. |
var myVariable = document.querySelector('h1');
All of the above examples too. |
So why do we need variables? Well, variables are needed to do anything interesting in programming. If values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change the image displayed in an image gallery.
<html> <body> <script type="text/javascript "> var age = 25; var name ="Superman"; alert( "The age of "+name+"is "+age+" years"); </script> <a href="Lesson1a.html ">Back to Lesson</a> </body> </html>